﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using uComponents.Core.DataTypes.DataTypeGrid.Functions;
using uComponents.Core.DataTypes.DataTypeGrid.Model;
using umbraco.MacroEngines;
using umbraco.MacroEngines.Library;

namespace uComponents.RazorModels.DataTypeGrid
{
	/// <remarks>
	/// We use the <c>uComponents.RazorModels.DataTypeGrid.StoredValueForModel</c> object 
	/// instead of the <c>uComponents.Core.DataTypes.DataTypeGrid.Model.StoredValue</c> object 
	/// to override the <c>uComponents.Core.DataTypes.DataTypeGrid.Model.StoredValue.Value</c> 
	/// property, as the type is <c>umbraco.interfaces.IDataType</c>, which we do not need to 
	/// access at the front-end.
	/// </remarks>
	public class StoredValueForModel : StoredValue
	{
		public int NodeType { get; set; }
		public new string Value { get; set; }
	}

	[RazorDataTypeModel("82CC7433-ACB3-4A7A-8AB3-A02EC6DD181E")] // WIP [LK]
	public class DataTypeGridModelBinder : IRazorDataTypeModel
	{
		public bool Init(int CurrentNodeId, string PropertyData, out object instance)
		{
			var values = new List<StoredValueRow>();

			if (!string.IsNullOrEmpty(PropertyData))
			{
			    var doc = new XmlDocument();
			    doc.LoadXml(PropertyData);

				var items = doc.DocumentElement;
				if (items.HasChildNodes)
			    {
			        foreach (XmlNode item in items.ChildNodes)
			        {
			
			            var valueRow = new StoredValueRow();
						if (item.Attributes != null)
			            {
							valueRow.Id = int.Parse(item.Attributes["id"].Value);
			            }

						foreach (XmlNode node in item.ChildNodes)
			            {
							var value = new StoredValueForModel();
							value.Alias = node.Name;
							value.Name = node.Attributes["nodeName"].Value;
							value.NodeType = int.Parse(node.Attributes["nodeType"].Value);
							value.Value = node.InnerText;

							valueRow.Cells.Add(value);
			            }

			            values.Add(valueRow);
			        }
			    }

			}

			instance = values;

			return true;
		}
	}
}